﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Ext.Net;
using Ext.Net.Utilities;
using MemberMgr.Data;
using MemberMgr.Data.BusinessObjects;
using MemberMgr.Data.ManagerObjects;
using System.Data;

namespace MemberMgr.Website.Admin
{
    public partial class RoleAdmin : Common.TabPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                //this.roleStore.DataSource = this.GetDataTable();
                //this.roleStore.DataBind();

                GetExamplesNodes(this.menuTree.Root);

            }

        }

        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable();
            string roleName = string.Empty;
            IList<tRole> list = null;

            dt.Columns.AddRange(new DataColumn[] { 
                new DataColumn(){ ColumnName="ID",DataType=typeof(int)},
                new DataColumn(){ ColumnName="ROLENAME",DataType=typeof(string)},
                new DataColumn(){ ColumnName="ROLEATTR",DataType=typeof(string)},
                new DataColumn(){ ColumnName="COMMENT",DataType=typeof(string)}
            });

            ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

            if (!string.IsNullOrEmpty(this.txtSearchName.Text.Trim()))
            {
                list = roleMgr.GetRoleInfoByName(this.txtSearchName.Text.Trim());
            }
            else
            {
                list = roleMgr.GetAll();
            }


            if (list != null)
            {
                foreach (tRole item in list)
                {
                    dt.Rows.Add(new object[] { 
                        item.Id,
                        item.Rolename,
                        item.Roleattr,
                        item.Comment
                    });
                }
            }

            return dt;
        }

        [DirectMethod]
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            DataTable dt = this.GetDataTable();

            this.roleStore.DataSource = dt;
            this.roleStore.DataBind();
        }

        [DirectMethod]
        protected void roleStore_RefreshData(object sender, StoreRefreshDataEventArgs e)
        {
            this.roleStore.DataBind();
        }

        [DirectMethod]
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string roleName = this.txtRoleName.Text.Trim();
                string roleAttr = this.txtRoleAttr.Text.Trim();
                string roleid = this.txtID.Text.Trim();
                string rolecomment = this.txtComment.Text.Trim();

                IList<string> list = new List<string>();

                //Get Role info
                foreach (string item in this.hidFunno.Text.Trim().Split(','))
                {
                    if (!string.IsNullOrEmpty(item))
                    {
                        list.Add(item);
                    }
                }

                if (string.IsNullOrEmpty(roleid))
                {
                    //Add
                    ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();
                 
                    roleMgr.Session.BeginTransaction();

                    try
                    {
                        tRole role = new tRole();
                        role.Rolename = roleName;
                        role.Comment = rolecomment;
                        role.Roleattr = roleAttr;

                        roleMgr.Save(role);

                        ItRightManager rightMgr = Common.CommonUtil.managerFactory.GettRightManager();

                        tRight right = null;

                        foreach (string item in list)
                        {
                            right = new tRight();

                            right.Rightno = item;
                            right.Righttype = "M";
                            right.TRole = role;

                            rightMgr.Save(right);
                        }

                        roleMgr.Session.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        Common.CommonUtil.logger.Error(ex.Message, ex);
                        roleMgr.Session.RollbackTransaction();
                    }
                    
                }
                else
                {
                    //Update
                    ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();
                    ItRightManager rightMgr = Common.CommonUtil.managerFactory.GettRightManager();

                    tRole role = roleMgr.GetById(uint.Parse(roleid));

                    if (role != null)
                    {
                        roleMgr.Session.BeginTransaction();

                        try
                        {
                            role.Rolename = roleName;
                            role.Comment = rolecomment;
                            role.Roleattr = roleAttr;

                            role.TRights.Clear();
                            
                            //Insert Right
                            tRight right = null;
                            foreach (string item in list)
                            {
                                right = new tRight();

                                right.Rightno = item;
                                right.Righttype = "M";
                                right.TRole = role;

                                role.TRights.Add(right);
                            }

                            roleMgr.Update(role);
                            roleMgr.Session.CommitTransaction();
                        }
                        catch (Exception ex)
                        {
                            Common.CommonUtil.logger.Error(ex.Message, ex);
                            roleMgr.Session.RollbackTransaction();
                        }
                        
                    }

                }

                DataTable dt = this.GetDataTable();

                this.roleStore.DataSource = dt;
                this.roleStore.DataBind();

                this.winRoleDetail.Hide();
            }
            catch (Exception ex)
            {
                Common.CommonUtil.logger.Error(ex.Message,ex);
            }
        }

        [DirectMethod]
        protected void roleGrid_RowDbClick(object sender, DirectEventArgs e)
        {
            //Get role information
            GetExamplesNodes(this.menuTree.Root);

            string id = e.ExtraParams["roleid"];
            tRole role = null;

            if (!string.IsNullOrEmpty(id))
            {
                ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

                role = roleMgr.GetById(uint.Parse(id));

                if (role != null)
                {
                    string strRight = string.Empty;

                    foreach (tRight right in role.TRights)
                    {
                        strRight += right.Rightno + ",";
                    }

                    this.panelDetail.SetValues(new
                    {
                        role.Id,
                        role.Roleattr,
                        role.Rolename,
                        role.Comment,
                        Rightstring = strRight
                    });
                }
                else
                {
                    return;
                }
            }
            else
            {
                return;
            }

            this.winRoleDetail.Show();
        }

        protected Ext.Net.TreeNodeCollection GetExamplesNodes(Ext.Net.TreeNodeCollection nodes)
        {
            if (nodes == null)
            {
                nodes = new Ext.Net.TreeNodeCollection();
            }
            else
            {
                nodes.Clear();
            }

            
            ItMenuManager menuManager = Common.CommonUtil.managerFactory.GettMenuManager();

            IList<tMenu> list = menuManager.GetAll();

            IList<tMenu> topLevel = list.Where(p => p.Menulevel == "0").ToList();

            Ext.Net.TreeNode rootNode, leftNode;
            Ext.Net.TreeNode topNode = new Ext.Net.TreeNode("菜单");
            if (topLevel != null)
            {
                foreach (tMenu item in topLevel)
                {
                    rootNode = new Ext.Net.TreeNode();
                    rootNode.Text = item.Menuname;
                    rootNode.Icon = (Icon)Enum.Parse(typeof(Icon), item.Menuico);
                    rootNode.Checked = ThreeStateBool.False;
                    rootNode.CustomAttributes.Add(new ConfigItem("funno", item.Menuno, ParameterMode.Value));

                    IList<tMenu> leftLevel = list.Where(p => p.Menuparent == item.Id).ToList();

                    foreach (tMenu left in leftLevel)
                    {
                        leftNode = new Ext.Net.TreeNode();
                        leftNode.Text = left.Menuname;
                        leftNode.Leaf = true;
                        leftNode.Icon = (Icon)Enum.Parse(typeof(Icon), left.Menuico);
                        leftNode.Checked = ThreeStateBool.False;
                        leftNode.CustomAttributes.Add(new ConfigItem("funno", left.Menuno,ParameterMode.Value));
                        rootNode.Nodes.Add(leftNode);
                    }

                    topNode.Nodes.Add(rootNode);
                }
            }

            topNode.Expanded = true;

            nodes.Add(topNode);

            this.menuTree.ExpandAll();
            return nodes;
        }

        private void CheckTree(Ext.Net.TreeNodeCollection nodes, IList<tRight> rights)
        {
            foreach (Ext.Net.TreeNode item in nodes)
            {
                if (item.CustomAttributes
                    .Where(l => l.Name == "funno").FirstOrDefault() != null &&
                    rights.Where(p => p.Rightno == item.CustomAttributes
                    .Where(l => l.Name == "funno").FirstOrDefault().Value).Count() > 0)
                {
                    item.Checked = ThreeStateBool.True;
                }
                else
                {
                    item.Checked = ThreeStateBool.False;
                }

                if (!item.Leaf && item.Nodes.Count > 0)
                {
                    CheckTree(item.Nodes, rights);
                }
            }
        }

        private void GetSelectedFun(Ext.Net.TreeNodeCollection nodes, ref IList<string> funlist)
        {
            foreach (Ext.Net.TreeNode item in nodes)
            {
                if (item.Leaf)
                {
                    if (item.Checked == ThreeStateBool.True)
                    {
                        funlist.Add(item.CustomAttributes.Where(l => l.Name == "funno").FirstOrDefault().Value);

                        if (!funlist.Contains(item.ParentNode.CustomAttributes.Where(l => l.Name == "funno").FirstOrDefault().Value))
                        {
                            funlist.Add(item.ParentNode.CustomAttributes.Where(l => l.Name == "funno").FirstOrDefault().Value);
                        }
                    }
                }
                else
                {
                    GetSelectedFun(item.Nodes, ref funlist);
                }
            }
        }

        [DirectMethod]
        protected void btnDelete_Click(object sender,DirectEventArgs e)
        {
            ItRoleManager roleMgr = Common.CommonUtil.managerFactory.GettRoleManager();

            try
            {
                if (e.ExtraParams["roleid"] == null && string.IsNullOrEmpty(e.ExtraParams["roleid"]))
                {
                    return;
                }

                uint roleid = uint.Parse(e.ExtraParams["roleid"].ToString());

                roleMgr.Session.BeginTransaction();

                tRole role = roleMgr.GetById(roleid);

                if (role != null)
                {
                    
                    roleMgr.Delete(role);
                }

                roleMgr.Session.CommitTransaction();

                DataTable dt = this.GetDataTable();

                this.roleStore.DataSource = dt;
                this.roleStore.DataBind();
            }
            catch (Exception ex)
            {
                roleMgr.Session.RollbackTransaction();
                Common.CommonUtil.logger.Error(ex.Message, ex);
            }
        }
    }
}
